//
//  WBStatusListViewModel.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/7.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import Foundation
import SDWebImage
import AVFoundation

/// 微博数据列表视图模型
class WBStatusListViewModel {
    lazy var statusList = [WBStatusViewModel]()
    
    /// 加载微博列表
    ///
    /// - parameter pullup:     是否是上拉刷新标记
    /// - parameter completion: 完成的回调
    func loadStatus(pullup: Bool, completion: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        let since_id = pullup ? 0 : (statusList.first?.status.id ?? 0)
        let max_id = !pullup ? 0 : (statusList.last?.status.id ?? 0)
        
        WBStatusListDAL.loadStatus(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            /// 判断网络请求是否成功
            if !isSuccess {completion(false, false)}
            
            /// 定义结果可变数组
            var array = [WBStatusViewModel]()
            
            /// 字典转模型
            for dict in list ?? [] {
                guard let model = WBStatus.yy_model(with: dict) else {
                    continue
                }
                array.append(WBStatusViewModel(model: model))
            }
            
            if pullup {
                self.statusList += array
            }else{
                self.statusList = array + self.statusList
                
                if array.count != 0 {
                    let url = Bundle.main.url(forResource: "msgcome.wav", withExtension: nil)
                    var id:SystemSoundID = 0
                    AudioServicesCreateSystemSoundID(url as! CFURL, &id)
                    AudioServicesPlaySystemSound(id)
                }
            }
            
            self.cacheSingleImage(list: array, finish: completion)
        }
    }
    
    /// 缓存本次下载微博数据组中的单张图像
    ///
    /// - parameter list: 本次下载的视图模型数组
    private func cacheSingleImage(list: [WBStatusViewModel], finish: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        
        let group = DispatchGroup()
        
        /// 记录数据长度
        var length = 0
        
        // 遍历数组，有单张图片的进行缓存
        for vm in list {
            if vm.picURLs?.count != 1 {
                continue
            }
            
            /// 代码走到这里，有且只有一张图片，因此该处可以强行解包，并且数组首位有对象
            guard let pic = vm.picURLs?[0].thumbnail_pic,
                let url = URL(string: pic) else {continue}
            
            debugPrint("要缓存的URL是\(url)")
            
            group.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                // 将图像转换成二进制数据
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    length += data.count
                    
                    // 图像缓存成功，更新配图视图大小
                    vm.updateSingleImageSize(image: image)
                }
                
                debugPrint("缓存的图像是\(image), 长度\(length/1024)k")
                
                group.leave()
            })
        }
        
        group.notify(queue: DispatchQueue.main) {
            debugPrint("缓存完成\(length/1024)k")
            
            finish(true, true)
        }
    }
}
